package com.stone.cat.adapter.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.stone.cas.pojo.CasUser;
import com.stone.cat.adapter.MyServiceExecutor;
import com.stone.cat.common.util.HttpClientUtil;
import com.stone.cat.common.util.MapUtil;
import com.stone.cat.facade.pojo.request.LoginRequestDTO;
import com.stone.cat.facade.pojo.response.CatBaseResponseDTO;
import com.stone.cat.facade.service.MyBaseService;
import com.stone.cat.facade.service.UserManagerService;
import com.stone.cat.persist.config.CASConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by 喵 on 2018/2/9.
 */
@Service
public class UserManagerServiceImpl extends MyBaseService implements UserManagerService {

    @Autowired
    private CASConfig casConfig;

    @Override
    public CatBaseResponseDTO login(LoginRequestDTO requestDTO) {
        return this.execute(requestDTO, CatBaseResponseDTO.class,
                new MyServiceExecutor<LoginRequestDTO, CatBaseResponseDTO>() {
            @Override
            protected void beforeProcess(LoginRequestDTO requestDTO) {
                requestDTO.valid();
            }

            @Override
            protected CatBaseResponseDTO myProcess(LoginRequestDTO requestDTO) {
                CatBaseResponseDTO responseDTO = CatBaseResponseDTO.of();
                String resultStr = HttpClientUtil.doPost(casConfig.getUrl(), MapUtil.objectToMap(requestDTO));
                JSONObject resultJSON = JSON.parseObject(resultStr);
                if (resultJSON.getInteger("code") == 0) {
                    CasUser user = (CasUser) resultJSON.get("data");
                    responseDTO.setData(user);
                }
                return responseDTO;
            }
        });
    }
}
